<?php

namespace control;

/*
*委外入库检验类
*/

class outsourceInspectionClass extends adIndexClass
{
	private const page  = 'outsourceInspection';
	private const table = 'quality_order';
	private const title = '委外入库检验';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => "单据日期",
                        'width' => 100,
                    ],
                    'sourceNo'  => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'supplier'         => [
                        'name'  => '供应商',
                        'width' => 150,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 100,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'batch'          => [
                        'name'  => '批次',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'num'          => [
                        'name'  => '收货数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'passNum'          => [
                        'name'  => '合格数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'badNum'          => [
                        'name'  => '不良数量',
                        'width' => 100,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ],
                    'checkTime'          => [
                        'name'  => '质检日期',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "状态" => checkbox(array('name' => 'state', 'value' => ['待质检', '已质检'], 'checked' => ['待质检'])),
                ],
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    '供应商' => selectMultiple(["name" => "supplierId", 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' and outsource='是'", 'sqlField' => 'name', 'class' => 'width200']),
                    "物料编码"   => text(array("name" => "code")),
                ],
                [
                    "物料名称" => text(array("name" => "materialName")),
                    "不良原因" => text(array("name" => "reason")),
                    '处置方式' => repeatSelect(array('name' => 'method', 'sqlForm' => " quarantine_reason where coid = '" . self::$coid . "'", 'sqlField' => 'method')),
                ],
                [
                    "质检日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . $this->get('cla') . "','operate',{act:'batch'})\" class='spanButton'>批量质检</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"a.sourceNo"     => $this->post('orderNo'),
			"b.code"         => $this->post('code'),
			"b.materialName" => $this->post('materialName'),
		);
		//全等查询数组
		$equal = array(
			"a.targetId" => $this->post('supplierId'),
			'a.coid'     => self::$coid,
		);
		$and   = " and a.type = 5";
		if ($this->post('createTime')) {
			$and .= self::timeComparison($this->post('createTime'), 'date', 'checkTime');
		}
		if ($this->post('reason')) {
			$and .= " and a.id in (select distinct orderId from quality_order_reason where coid = '" . self::$coid . "' and reasonId in (select id from quarantine_reason where coid = '" . self::$coid . "' and reason like '%" . $this->post('reason') . "%')) ";
		}
		if ($this->post('method')) {
			$and .= " and a.id in (select distinct orderId from quality_order_reason where coid = '" . self::$coid . "' and reasonId in (select id from quarantine_reason where coid = '" . self::$coid . "' and dealMethod = '" . $this->post('method') . "')) ";
		}
		if ($this->post('state')) {
			$and .= " and a.state in ('" . implode("','", $this->post('state')) . "')";
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.time desc,a.list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array(
		    "table" => self::table . " as a join material as b on a.materialId = b.id",
            'field' => "a.*,b.name,b.code,b.model",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate           = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'recordDate':
                        $outsource_in_order = query('outsource_in_order', "id = '$array[sourceId]'");
                        $row[] = $outsource_in_order['recordDate'];
                        break;
                    case 'supplier':
                        $row[] = supplierClass::getName($array['targetId']);
                        break;
                    case 'num':
                    case 'passNum':
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case 'badNum':
                        $row[] = $array['state'] == '待质检' ? 0 : self::lostZero($array['num'] - $array['passNum'],'numPrecision');
                        break;
                    case 'checkTime':
                        $row[] = self::null($array['checkTime']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table . " as a join material as b on a.materialId = b.id",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num,ifnull(sum(a.passNum),0) as passNum,ifnull(sum(if(a.state='待质检',0,a.num-a.passNum)),0) as badNum",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'passNum'        => self::lostZero($totalQuery['passNum'], 'numPrecision'),
            'badNum' => self::formattingFigure($totalQuery['badNum'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/**
	 * 提交
	 *
	 * @return bool|string
	 */
	public function detailEdit()
	{
		$id              = $this->post('id');
		$itemIdArr       = $this->post('itemId') ?: [];
		$resultOptionArr = $this->post('resultOption');
		$itemTextArr     = $this->post('itemText');
		$reasonIdArr     = $this->post('reasonId') ?: [];
		$reasonOptionArr = $this->post('reasonOption');
		$reasonNumArr    = $this->post('reasonNum') ?: [];
		$mxTextArr       = $this->post('mxText');

		$field      = [
			'state'     => '已质检',
			'checkId'   => self::$stid,
			'checkTime' => $this->time,
			'passNum'   => $this->post('passNum') ? self::formattingFigure($this->post('passNum'), 'numPrecision') : '',
		];
		$annotation = [
			'passNum' => '合格数量',
		];
		$rules      = [
			'passNum' => 'required|numeric',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($itemIdArr)) {
			$json['warn'] = '未找到质检项目';
		} elseif (static::is_null_array($resultOptionArr)) {
			$json['warn'] = '请选择结果选项';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此委外入库检验单';
		} elseif (!empty($reasonIdArr) && static::is_null_array($reasonNumArr)) {
			$json['warn'] = '请填写不良数量';
		} elseif ($info['state'] !== '待质检') {
			$json['warn'] = '此委外入库检验单不是待质检状态，不能编辑';
		} elseif ($info['num'] < $field['passNum']) {
			$json['warn'] = '合格数量超出了总数量';
		} elseif (round(array_sum($reasonNumArr), 2) != round($info['num'] - $field['passNum'], 2)) {
			$json['warn'] = '不良明细中数量之和不等于总的不良数量';
		} else {
				$this->startTrans();
				$isPass       = true;//事务通过标志
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
				foreach ($itemIdArr as $k => $nid) {
					$mx = query(self::table . "_item", "id = '$nid'");
					if ($mx['id']) {
						$warn = static::update([
							"table" => self::table . "_item",
							"field" => [
								'options' => $resultOptionArr[$nid],
								'text'    => $itemTextArr[$k],
							],
							"where" => " id = '$nid'",
						]);
						if (!in_array($warn, ['新增成功', '更新成功'])) {
							$isPass       = false;
							$json['warn'] = $warn;
							break;
						}
					}
				}
				//添加或更新质检不良原因
				if (is_array($reasonIdArr)) {
					foreach ($reasonIdArr as $k => $nid) {
						$mx                = query(self::table . "_reason", "id = '$nid'");
						$quarantine_reason = query('quarantine_reason', "id = '$reasonOptionArr[$k]'");
						$reasonNumArr[$k]  = self::formattingFigure($reasonNumArr[$k], 'numPrecision');
						if (!empty($mx['id'])) {
							//更新
							$warn = static::update([
								"table" => self::table . "_reason",
								"field" => [
									'reasonId'   => $reasonOptionArr[$k],
									'num'        => $reasonNumArr[$k],
									'dealMethod' => $quarantine_reason['method'],
									'text'       => $mxTextArr[$k],
								],
								"where" => " id = '$nid'",
							]);
						} else {
							//新增
							$warn = static::insert([
								"table" => self::table . "_reason",
								"field" => [
									'id'         => $nid,
									'orderId'    => $id,
									'coid'       => self::$coid,
									'reasonId'   => $reasonOptionArr[$k],
									'num'        => $reasonNumArr[$k],
									'dealMethod' => $quarantine_reason['method'],
									'text'       => $mxTextArr[$k],
								],

							]);
						}
						if (!in_array($warn, ['新增成功', '更新成功'])) {
							$isPass       = false;
							$json['warn'] = $warn;
							break;
						}
					}
				}

				if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
					$this->commitTrans();
					delete(array('table' => self::table . "_reason", 'where' => " id not in ('" . implode("','", $reasonIdArr) . "') and orderId = '$id'"));
                    //改变待入库单质检状态
                    inStockClass::qualityInventory($info);

					auditingFollow(array(
						"type"   => "委外入库检验单",
						"typeId" => $info['id'],
						"text"   => "【{$this->control['name']}】确认",
					));
					//添加日志
					$type = mb_substr($json['warn'], 0, 2, 'utf-8');
					$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
					$this->logText(["type" => self::page, "text" => $text]);
					//返回
					$_SESSION['warn'] = $json['warn'];
					$json['warn']     = 2;
					$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
				} else {
					$this->rollback();
				}
		}

		resp:
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data = array(
				"id" => $info['id'],
			);

			$button = [];
            $edit   = false;
			if ($this->power(self::page, "edit") && $info['state'] != '已质检') {
                $edit = true;
				//按钮
				$button[] = [
					'style' => 'li-btn-blue-bg',
					"name"  => "提交",
					"type"  => "点击事件",
					"title" => "提交",
					'fun'   => "subForm('detailForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detailEdit')",
				];
			}
			if ($this->power(self::page, "cancel") && $info['state'] == '已质检') {
				$button[] = [
					"name"  => "撤回",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'cancel', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			/*****质检项目********/
			$tr[]   = ['质检项', '检验标准', '结果选项', '备注'];
			$result = find(array('table' => self::table . "_item", 'where' => "orderId = '$info[id]' order by list"));
			foreach ($result['array'] as $k=>$array) {
				$quarantine_item = query('quarantine_item', "id = '$array[itemId]'");
				$tr[]            = [
					hidden(array('name' => 'itemId[]', 'value' => $array['id'])) .
					$quarantine_item['name'],
					$quarantine_item['standard'],
                    $edit ? radio(array('name' => "resultOption[$array[id]]", 'checked' => $array['options'], 'value' => $quarantine_item['result'] ? explode('，', $quarantine_item['result']) : [])) : $array['options'],
                    $edit ? text(array('name' => 'itemText[]', 'class' => 'text', 'value' => $array['text'])) : $array['text'],
				];
			}

			/*****不良原因********/
			$reason[] = array_merge(($edit ? [''] : []),['不良原因', '不良数量', '处置方式', '备注', '状态', '处理人', '处理日期']);
            $result = find(array(
                'field' => "id as reasonId,reasonId as reasonOption,num as reasonNum,dealMethod,text as mxText,state,dealId,dealDate",
                'table' => self::table . "_reason where orderId = '$info[id]' order by list"
            ));
            if(count($result['array']) > 0) {
                foreach ($result['array'] as $k=>$array) {
                    $array['list'] = $k+1;
                    $array['dealId'] = self::findStaff($array['dealId']);
                    $array['dealDate'] = self::null($array['dealDate']);
                    $reason[] = $this->listRow($array, $edit, $info['qid']);
                }
            }else{
                $reason[] = $this->listRow(['reasonId'=>self::getId(), 'list'=>1], $edit, $info['qid']);
            }
            $total      = [
                $edit?2:1  => "<span id='total_num'>" . self::lostZero(array_sum(array_column((array)$result['array'],'reasonNum')),'num') . "</span>",
            ];
			$supplier    = query('supplier', "id = '$info[targetId]'");
			$source      = query($info['sourceTable'], "id = '$info[sourceId]'");
			$material    = query('material', "id = '$info[materialId]'");
			$quarantine  = query('quarantine', "id = '$info[qid]'");
			$setting     = optionSettingClass::getSetting('质量');
			if ($info['updateTime'] == $info['time'] && $info['state'] == '待质检' && isset($setting['checkOrderDefault']['val']) && $setting['checkOrderDefault']['val'] == '单据数量') {
				$info['passNum'] = $info['num'];
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->edit4(array(
				'基本信息' => array(
					array(
						"供应商"   => $supplier['name'],
						"单据编号" => $info['sourceNo'],
						"单据日期" => $source['recordDate'],
                        "物料" => $material['code'] . '-' . $material['name'] . '-' . $material['model'],
					),
					array(
                        "批次" => $info['batch'],
						"收货数量(" . $info['unit'] . ")" => "<span id='completeNum'>" . self::lostZero($info['num'], 'numPrecision') . "</span>",
						"合格数量(" . $info['unit'] . ")" => $edit ? text(array('name' => 'passNum', 'blur' => 'getScrap', 'other' => self::digitalFiltering('numPrecision'), 'class' => 'text textPrice', 'value' => self::lostZero($info['passNum'], 'numPrecision'))) : self::lostZero($info['passNum'], 'numPrecision'),
						"不良数量(" . $info['unit'] . ")" => "<span id='scrap'>" . ($info['state'] == '待质检' ? 0 : $info['num'] - $info['passNum']) . "</span>",
					),

				),
				'检验方案' => array(
					array(
						"质检方式" => $quarantine['qualityType'],
						"抽检比例" => ($quarantine['proportion'] * 100) . '%',
						"抽检数量" => $info['num'] * $quarantine['proportion'],
					),
					array(
						'检验要求' => pre($quarantine['mandate']),
					),
					array(
						fileUploadClass::showFile($quarantine['id'], '质检方案'),
					),
				),
			));
            $tableStyle = $edit?'editList':'detailList';
            $data['html'] .= $this->$tableStyle([
                'title' => '质检项目',
                'html' => $this->listTable(array('tr' => $tr, 'end' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->$tableStyle([
                'title' => '不良明细',
                'html' => $this->listTable(array('tr' => $reason, 'end' => true, 'showSort' => !$edit, 'total' => $total)),
            ]);
            $data['html']   .= $this->edit4(array(
                '系统信息' => array(
                    array(
                        "质检单号" => $info['orderNo'] . hidden(array('name' => 'id', 'value' => $info['id'])),
                        "质检人"   => self::findStaff($info['checkId']),
                        "质检时间" => $info['checkTime'],
                    ),
                ),
            ));
			$data['html'] .= $this->js() . <<<efo
<style>
.display-hidden{border: none}
.display-hidden:focus{border: 1px solid #d7d7d7;line-height: 16px;
    height: 16px;
    width: 200px;
    padding: 6px;
    border-radius: 4px;}
</style>
efo;
			$data['html'] = "<form name='detailForm'>" . $data['html'] . "</form>";

			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	public function js(): string
	{
		return <<<eof
<script>
//计算不合格数量
function getScrap(e){
    let total = Number($("#completeNum").html());
    let passNum = e.value;
    $("#scrap").html((total-passNum).toFixed(publicSettings.numPrecision.num))
}
function getDealMethod(e){
    let val = e.value;
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getDealMethod',{id:val},function (res){
               $(e).parent().parent().find(".dealMethod").html(res.data);
             },'json');
}
function addRow(e,qid){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{qid:qid},function (res){
                 $(e).closest('tr').after(res.data);
                resetNumber($(e).closest('tbody'))
                calculateTotal()
             },'json');
}
//计算计划数量
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let num = 0
    table.find("[name='reasonNum[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
</script>
eof;
	}

	/**
	 * 获取处置方式
	 *
	 * @return bool|string
	 */
	public function getDealMethod(): bool|string
	{
		$id                = $this->post('id');
		$quarantine_reason = query('quarantine_reason', "id = '$id'");
		$json['data']      = $quarantine_reason['method'];
		return json_encode($json, 320);
	}

    /**
     * Desc : 不良原因
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @param mixed $edit
     * @param string $qid
     * @return array|false|string
     */
    public function listRow($data=[], $edit = true, $qid = '')
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['reasonId'])&&$data['reasonId']?$data['reasonId']:self::getId();
        $qid = $qid?:$this->post('qid');
        $field = ['reasonOption', 'reasonNum', 'dealMethod', 'mxText', 'state', 'dealId', 'dealDate'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => ['reasonOption', 'reasonNum', 'mxText'],
            'nodeTextByClass' => ['dealMethod', 'state', 'dealId', 'dealDate'],
            'para' => ['qid'=>$qid],
            'callback' => "calculateTotal()",
        ],320);
        $delArg = json_encode([
            'empty' => ['reasonOption', 'reasonNum', 'mxText'],
            'emptyByClass' => ['dealMethod', 'state', 'dealId', 'dealDate'],
        ],320);
        $quarantine_reason = query("quarantine_reason", " id = '" . $array['reasonOption'] . "' ");
        $listArr = $edit ? [componentClass::tablePperation($list, "delRows(this,$delArg);calculateTotal()","cloneRows(this,$cloneArg)", "addRow(this,'$qid')")] : [];
        $tr = array_merge($listArr,[
            hidden(array('name' => 'reasonId[]', 'value' => $mxId)) .
            ($edit ? idSelect(array('name' => 'reasonOption[]', 'change' => 'getDealMethod', 'class' => 'select', 'value' => $array['reasonOption'], 'sqlForm' => "quarantine_reason where coid = '" . self::$coid . "' and orderId = '$qid' order by list asc", 'sqlId' => "id", 'sqlField' => "reason", 'title' => '不良原因')) : $quarantine_reason['reason']),
            $edit ? text(array('name' => 'reasonNum[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ", 'value' => self::lostZero($array['reasonNum'], 'numPrecision'))) : self::lostZero($array['reasonNum'], 'numPrecision'),
            "<span class='dealMethod'>{$array['dealMethod']}</span>",
            $edit ? text(array('name' => 'mxText[]', 'class' => 'text', 'value' => $array['mxText'])) : $array['mxText'],
            "<span class='state'>{$array['state']}</span>",
            "<span class='dealId'>{$array['dealId']}</span>",
            "<span class='dealDate'>{$array['dealDate']}</span>",
        ]);
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

	/**
	 *添加一行
	 */
	public function addRow()
	{
		$qid          = $this->post('qid');//质检方案ID
        $res = json_decode($this->listRow(qid: $qid),true);
        $json['data'] = $res['html'];
		return json_encode($json, 320);
	}

	/**
	 * 批量质检
	 */
	public function batchEdit(): bool|string
	{
		$idArr = $this->post('listId');

		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($idArr) || !is_array($idArr)) {
			$json['warn'] = '请选择数据';
		} else {
			$text = '';
			$x    = 0;
			foreach ($idArr as $id) {
				$info = query('quality_order', "id = '$id'");
				if (empty($info['id'])) {
					$text .= "未找到质检单<br>";
				} elseif ($info['state'] != '待质检') {
					$text .= "单据编号【{$info['sourceNo']}】,批次【{$info['batch']}】不是待质检状态<br>";
				} else {
					$warn = static::update([
						"table" => self::table,
						"field" => [
							'state'     => '已质检',
							'checkId'   => self::$stid,
							'checkTime' => $this->time,
							'passNum'   => $info['num'],
						],
						"where" => "id = '$info[id]'",
					]);
					if ($warn == '更新成功') {
						$x++;
						$text .= "单据编号【{$info['orderNo']}】,批次【{$info['batch']}】质检成功<br>";
						$all  = find(array('table' => self::table . "_item", "where" => "orderId = '$info[id]' order by list asc"));
						foreach ($all['array'] as $array) {
							$quarantine_item = query('quarantine_item', "id = '$array[itemId]'");
							static::update([
								"table" => self::table . "_item",
								"field" => [
									'options' => explode('，', $quarantine_item['result'])[0] ?? '',
								],
								"where" => " id = '$array[id]'",
							]);
						}
                        //改变待入库单质检状态
                        inStockClass::qualityInventory($info);

					} else {
						$text .= "单据编号【{$info['orderNo']}】,批次【{$info['batch']}】质检失败<br>";
					}
				}
			}
			if ($text) {
				$this->logText(["type" => self::page, "text" => $this->control['name'] . '批量质检情况如下：' . $text]);
			}
			$json['warn']     = 2;
			$_SESSION['warn'] = '成功质检了' . $x . '条数据';
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 撤回
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'     => '待质检',
			'checkId'   => '',
			'checkTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = '你还没有撤回权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此质检单';
		} elseif ($info['state'] != '已质检') {
			$json['warn'] = '此质检单不是已质检状态，无需撤回';
		} elseif (static::total(array('table' => 'quality_order_reason', 'where' => "orderId = '$id' and state = '已处理'")) > 0) {
			$json['warn'] = '此委外入库检验单已处理，不能撤回';
		} elseif (static::total(array('table' => 'inventory', 'where' => "sourceId = '$info[sourceId]' and state != '待入库' and classify = 1 and coid = '" . self::$coid . "'")) > 0) {
			$json['warn'] = '此委外入库检验单对应的入库单已入库，不能撤回';
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //改变待入库单质检状态
                inStockClass::qualityInventory($info, false);

				auditingFollow(array(
					"type"   => "委外入库检验单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】撤回",
				));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = $word = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			case 'batch':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认批量质检所选择的数据？';
				$function = 'batchEdit';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤回';
				$title    = '是否确认撤回此质检单？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}


}
